{layout name="layout" /}
<blockquote class="layui-elem-quote layui-quote-nm">
    <p>注意事项：</p>
    <p>1.路由格式必须严格遵循：/应用名称/控制器名称（驼峰转小写加下划线）/方法名称（驼峰写法，首字母小写）/其他参数（可选）</p>
    <p>2.控制器不允许出现大写字母，应全小写形式</p>
    <p>3.未添加在菜单的路由将不参与权限验证，如您需要给菜单的修改功能设置权限，应先将修改接口的路由添加到菜单中并设置路由</p>
    <p>4.修改菜单名称时，请删除 " |—— " 连接符</p>
</blockquote>
<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addMenu">添加</button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="getCheckData">删除选中行</button>
        <!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->
        <!--        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>-->
    </div>
</script>

<script type="text/html" id="barDemo">
    <!--    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script type="text/html" id="positionTpl">
    <input type="checkbox" name="position" value="{{d.id}}" lay-skin="switch" lay-text="侧边栏|顶部导航" lay-filter="position" {{ d.position == 0 ? 'checked' : '' }}>
</script>

<script type="text/html" id="statusTpl">
    <input type="checkbox" name="status" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁止" lay-filter="status" {{ d.status == 1 ? 'checked' : '' }}>
</script>

<script type="text/html" id="showTpl">
    <input type="checkbox" name="show" value="{{d.id}}" title="显示" lay-filter="show" {{ d.show == 1 ? 'checked' : '' }}>
</script>
<script>
    layui.use(['table','util'], function(){
        var table = layui.table;
        var util = layui.util;
        var form = layui.form;

        table.render({
            elem: '#test'
            ,url:'/admin/menu/getMenuListJson'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,title: '菜单列表'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true}
                ,{field:'title', title:'标题', fixed: 'left',edit:'text',width:220, sort: true}
                ,{field:'parent_id', title:'上级ID', edit:'text',width:100, sort: true, templet: function(res){
                        if(res.parent_id === 0){
                            return 0;
                        }else
                            return res.parent_id;
                    }
                }
                ,{field:'icon', title:'图标', edit:'text',width:80, templet: function(res){
                        return '<em>'+ res.icon +'</em>'
                    }}
                ,{field:'route', title:'路由', edit:'text',width:250}
                ,{field:'position', title:'展示位置', width:120,templet: '#positionTpl', unresize: true}
                ,{field:'status', title:'状态', width:100,templet: '#statusTpl', unresize: true}
                ,{field:'show', title:'是否显示', width:120,templet: '#showTpl', unresize: true}
                ,{field:'sort', title:'权重',edit:'text', width:100, sort: true}
                ,{field:'create_time', title:'创建时间', width:180}
                // ,{field:'update_time', title:'更新时间', width:120}
                ,{fixed:'right', title:'操作', toolbar: '#barDemo', width:70}
            ]]
            ,page: true
            ,limit: 20 //默认每页显示条数
        });
        //监听展示位置操作
        form.on('switch(position)', function(obj){
            console.log('id:'+this.value,'key:'+this.name,'value:'+obj.elem.checked, obj.othis);
            //调用修改权重接口
            var value = obj.elem.checked ? 0:1;
            var editData = [
                {
                    'id':this.value,
                    [this.name]:value
                }
            ];
            $.ajax({
                url: "/admin/menu/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });

        //监听状态操作
        form.on('switch(status)', function(obj){
            console.log('id:'+this.value,'key:'+this.name,'value:'+obj.elem.checked, obj.othis);
            //调用修改权重接口
            var value = obj.elem.checked ? 1:0;
            var editData = [
                {
                    'id':this.value,
                    [this.name]:value
                }
            ];
            $.ajax({
                url: "/admin/menu/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });

        //监听显示操作
        form.on('checkbox(show)', function(obj){
            console.log('id:'+this.value,'key:'+this.name,'value:'+obj.elem.checked, obj.othis);
            //调用修改权重接口
            var value = obj.elem.checked ? 1:0;
            var editData = [
                {
                    'id':this.value,
                    [this.name]:value
                }
            ];
            $.ajax({
                url: "/admin/menu/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    var idArray=[];
                    data.filter(item =>{
                        idArray.push(item.id);
                    })
                    layer.confirm('真的删除行么', function(index){
                        //layer.alert(JSON.stringify(data));
                        console.log('idArray:',idArray);
                        layer.close(index);
                        //调用删除接口
                        $.ajax({
                            url: "/admin/menu/del",
                            type: "POST",
                            data:{
                                'idArray':idArray
                            },
                            dataType: "json",
                            success: function(result){
                                console.log(result)
                                if(result.code === 0){
                                    layer.msg(result.msg);
                                    location.reload();
                                }
                            },
                            error:function(err){
                                console.log(err.statusText);
                            }
                        });
                    });
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;
                case 'addMenu':
                    window.open('/admin/menu/add');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听单元格编辑
        table.on('edit(test)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
            if(field === 'sort'){
                if (!(/(^[1-9]\d*$)/.test(util.escape(value)))) {
                    layer.msg('输入值无效，请输入非零开头的正整数');
                    return false;
                }
            }
            if(util.escape(value) > 9999){
                layer.msg('输入值应该小于等于9999');
                return false;
            }
            console.log('[ID: '+ data.id +'] ' + field + ' 字段更改值为：'+ util.escape(value));
            var editData = [
                {
                    'id':data.id,
                    [field]:util.escape(value)
                }
            ];
            console.log(editData);
            //调用修改权重接口
            $.ajax({
                url: "/admin/menu/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                var idArray=[];
                idArray.push(data.id);
                layer.confirm('真的删除行么', function(index){
                    console.log("删除:"+idArray);
                    obj.del();
                    layer.close(index);
                    //调用删除接口
                    $.ajax({
                        url: "/admin/menu/del",
                        type: "POST",
                        data:{
                            'idArray':idArray
                        },
                        dataType: "json",
                        success: function(result){
                            console.log(result)
                            if(result.code === 0){
                                layer.msg(result.msg);
                                location.reload();
                            }
                        },
                        error:function(err){
                            console.log(err.statusText);
                        }
                    });
                });
            } else if(obj.event === 'edit'){
                layer.prompt({
                    formType: 2
                    ,value: data.email
                }, function(value, index){
                    obj.update({
                        email: value
                    });
                    layer.close(index);
                });
            }
        });
    });
</script>
